package com.baizhi.wxt.service;

import com.baizhi.wxt.dao.UserMapper;
import com.baizhi.wxt.entity.User;
import com.baizhi.wxt.entity.UserExample;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Map<String, Object> queryAllPage(int page, int pageSize) {
        Map<String,Object> map = new HashMap<String,Object>();
        //调用dao 分页
        UserExample userExample = new UserExample();
        RowBounds rowBounds = new RowBounds((page - 1) * pageSize, pageSize);
        List<User> userList = userMapper.selectByExampleAndRowBounds(userExample,rowBounds);

        //调dao 查总行数
        int totalCount = userMapper.selectCount(null);

        map.put("page",page);
        map.put("total",totalCount);
        map.put("rows",userList);

        return map;
    }

    //修改状态         
    @Override
    public Map<String, Object> update(User user) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            User user1 = new User();
            user1.setId(user.getId());
            user1.setStatus(user.getStatus());

            //添加修改条件
            UserExample userExample = new UserExample();
            userExample.createCriteria().andIdEqualTo(user.getId());

            userMapper.updateByExampleSelective(user1,userExample);
            map.put("message","修改成功");
            map.put("status",200);
        }catch (Exception e){
            map.put("message","修改失败！！");
            map.put("status",400);
        }
        return map;
    }

    //删除
    @Override
    public Map<String, Object> delete(User user) {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            //调用dao

            User user1 = new User();
            user1.setId(user.getId());
            userMapper.delete(user1);
            map.put("message","删除成功");
            map.put("status",200);
        }catch (Exception e){
            e.printStackTrace();
            map.put("message","删除失败");
            map.put("status",400);
        }
        return map;
    }

}
